package dao

import (
	"Management/common"
	"Management/model"
)
//新建用户信息
func AddUser(name string,phone string,department_id int)(err error){
	db:=common.InitDB()
	user:=model.User{
		Name: name,
		Phone: phone,
		DepartmentID: department_id,
	}
	err=db.Create(&user).Error
	return err
}
//Id查询用户
func QueryUser(id int)(user model.User){
	db:=common.InitDB()
	db.Where("id =?").First(&user)
	return user
}
//分页查询当前部门的所有人
func QueryDepartmentUsers(pagenumber int,department_id int)(users []model.User,total int64,pagenumber1 int,pagesize int){
	db:=common.InitDB()
	//分页查询
	pagesize= 10
	//返回一个总数total
	//判断是否分页
	if pagesize==0{
		pagesize=-1
	}
	offsetval:=(pagenumber-1)*pagesize
	if pagenumber==-1{
		offsetval=-1
	}
	db.Where("department_id =?",department_id).Model(users).Count(&total).Limit(pagesize).Offset(offsetval).Order("id desc").Find(&users)
	return users,total,pagenumber,pagesize
}
//删除部门人员
func DeleteUser(phone string)(err error)  {
	db:=common.InitDB()
	var user model.User
	err=db.Where("phone =?",phone).Unscoped().Delete(&user).Error
	return err
}
//修改人员信息
func ChangeUser(id int,name string,phone string)(err error){
	db:=common.InitDB()
	var user model.User
	err=db.Where("id = ?",id).First(&user).Update("name",name).Update("phone",phone).Error
	return err
}
//模糊查询人员
func QueryLikeUsers(pagenumber int,name string,phone string)(users []model.User,total int64,pagenumber1 int,pagesize int){
	db:=common.InitDB()
	//分页查询
	pagesize= 10
	//返回一个总数total
	//判断是否分页
	if pagesize==0{
		pagesize=-1
	}
	offsetval:=(pagenumber-1)*pagesize
	if pagenumber==-1{
		offsetval=-1
	}
	db.Where("name like (?) && phone like (?)","%"+name+"%","%"+phone+"%").Model(users).Count(&total).Limit(pagesize).Offset(offsetval).Order("id desc").Find(&users)
	return users,total,pagenumber,pagesize
}